﻿using Common;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Options;
using ModelDto;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AssetManegement.Filter
{
    /// <summary>
    /// token 过滤
    /// </summary>
    public class MyTokenFilterAttribute : Attribute, IActionFilter, IFilterMetadata
    {
        private readonly IRedisHelper _redisHelper;
        private readonly IAccountService _AccountService;
        private readonly IOptions<AppsettingConfig> AppConfig;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="redisHelper"></param>
        public MyTokenFilterAttribute(IRedisHelper redisHelper, IOptions<AppsettingConfig> option, IAccountService AccountService)
        {
            _redisHelper = redisHelper;
            AppConfig = option;
            _AccountService = AccountService;
        }

        /// <summary>
        /// 后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //Console.WriteLine("111111111"); 
        }
        /// <summary>
        /// 前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var  curretnPath= context.HttpContext.Request.Path.Value.ToLower();

            if (AppConfig.Value.Debug == "1")
            {
                var tempUser = _AccountService.Query(a=>true);

                AccountLoginInfo accountLoginInfo = new AccountLoginInfo();

                accountLoginInfo.Account = tempUser;
                accountLoginInfo.PowerCode = "-1";



                string token = Guid.NewGuid().ToString("N").ToUpper();

                _redisHelper.SetValue(token, Newtonsoft.Json.JsonConvert.SerializeObject(accountLoginInfo), new TimeSpan(2, 0, 0));


                //var res = _redisHelper.GetValue($"{ConstBase.Cache_UserLogin}{account.AccountNo}");

                //if (!string.IsNullOrWhiteSpace(res))
                //{
                //    _redisHelper.SetValue($"{ConstBase.Cache_UserLogin}{account.AccountNo}", "0", new TimeSpan(0, 2, 0));
                //}


                //缓存时间2小时滑动时间
                _redisHelper.SetValue(token, JsonConvert.SerializeObject(accountLoginInfo), new TimeSpan(2, 0, 0));

                //context.HttpContext.Request.Headers["LUserInfo"] = JsonConvert.SerializeObject(accountLoginInfo);
                context.HttpContext.Request.Headers.Add("LUserInfo", JsonConvert.SerializeObject(accountLoginInfo));
            }
            else
            {
                if (curretnPath.Contains("jiangjieadmin/uploadfile"))//&& AppConfig.Value.Debug == "1")
                {
                    //跳过
                }
                else
                {
                    string token = context.HttpContext.Request.Headers["Token"].ToString();
                    if (string.IsNullOrWhiteSpace(token))
                    {
                        //TOKEN 无效
                        context.Result = new JsonResult(new JsonResultL().TokenFail());

                    }
                    else
                    {
                        string tokenCache = _redisHelper.GetValue(token);
                        if (string.IsNullOrWhiteSpace(tokenCache))
                        {
                            //TOKEN 无效
                            context.Result = new JsonResult(new JsonResultL().TokenFail());

                        }
                        else
                        {
                            //判断用户是否正常
                            AccountLoginInfo CurrentUser = JsonConvert.DeserializeObject<AccountLoginInfo>(tokenCache);
                            if (CurrentUser == null || CurrentUser.Account == null)
                            {
                                //TOKEN 无效
                                context.Result = new JsonResult(new JsonResultL().TokenFail());
                            }
                            else
                            {
                                var tempUser = _AccountService.Find(CurrentUser.Account.Id);

                                if (tempUser == null || tempUser.EnableState != 1)
                                {
                                    //TOKEN 无效
                                    context.Result = new JsonResult(new JsonResultL().TokenFail());
                                }
                                else
                                {
                                    //缓存时间2小时滑动时间
                                    _redisHelper.SetValue(token, tokenCache, new TimeSpan(2, 0, 0));

                                    context.HttpContext.Request.Headers.Add("LUserInfo", tokenCache);// ["LUserInfo"] = tokenCache;
                                }


                            }


                        }

                    }
                }

            }

        }
    }
}
